package com.lhl.mq.mqServer.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Exchange {
    //此处的 name 作为交换机的身份标识（唯一的）
    private String name;
    //交换机类型，DIRECT FANOUT TOPIC
    private ExchangeType type = ExchangeType.DIRECT;
    //该交换机是否要持久化存储，true 表示要持久化， false 表示不需要持久化
    private boolean durable = false;
    //预留字段，无人使用时是否自动删除
    private boolean autoDelete = false;
    //预留字段，交换机的其他属性
    private Map<String, Object> arguments = new HashMap<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ExchangeType getType() {
        return type;
    }

    public void setType(ExchangeType type) {
        this.type = type;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }


   public String getArguments(){
       ObjectMapper objectMapper = new ObjectMapper();
       //将变量 arguments 进行序列化
       try {
           return objectMapper.writeValueAsString(arguments);
       } catch (JsonProcessingException e) {
           e.printStackTrace();
       }

       return "{}";
   }


   //从数据库中读数据
   public void setArguments(String argumentsJson){
        ObjectMapper objectMapper = new ObjectMapper();
        //将变量 arguments 进行反序列化
       try {
           //赋值给当前对象的 argument 属性
          this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<Map<String,Object>>() {});
       } catch (JsonProcessingException e) {
           e.printStackTrace();
       }
   }


    //这组get、set方法主要是提供给java内部代码使用，这样取值和赋值都会比较方便
    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key,Object value){
        arguments.put(key,value);
    }

    public void setArguments(Map<String,Object> arguments){
        this.arguments = arguments;
    }

    @Override
    public String toString() {
        return "Exchange{" +
                "name='" + name + '\'' +
                ", type=" + type +
                ", durable=" + durable +
                ", autoDelete=" + autoDelete +
                ", arguments=" + arguments +
                '}';
    }
}
